package com.zhongshengnetwork.rightbe.clerk.view;

import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.BezierRadarHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhongshengnetwork.rightbe.Adv.model.AdvertUtils;
import com.zhongshengnetwork.rightbe.Adv.model.SPManageUtils;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.clerk.adapter.ClerkAdapter;
import com.zhongshengnetwork.rightbe.common.AppThemeUtils;
import com.zhongshengnetwork.rightbe.common.BaseAnalyticsFragment;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.ScreenUtils;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.gsonmodel.LangInfoModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ClerkRecyclerFragment extends BaseAnalyticsFragment {

    private int pageindex = 0;
    private static final int Records = 13;
    private boolean isHasMore = false;
    public int dataType = 0; //0-最新文案列表；1-用户文案列表
    private View rootView;//缓存Fragment view
    private RecyclerView clerk_recycler_view;

    private int imgW = 0;
    private float density = 0.0f;
    private int screenWidth = 0;
    private ClerkAdapter clerkAdapter;

    private RefreshLayout mRefreshLayout;
    private LangInfoModel mLangInfoModel;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        calculateImageWidth();
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.clert_recycler_layout, container, false);
            pageindex = 0;
            int width = ScreenUtils.getScreenWidth(getActivity());
            density = ScreenUtils.getScreenDensity(getActivity());
            screenWidth = width;
            clerk_recycler_view = (RecyclerView) rootView.findViewById(R.id.clerk_recycler_view);
            LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
            clerk_recycler_view.setLayoutManager(layoutManager);
            clerkAdapter = new ClerkAdapter(getActivity(), imgW);
            clerk_recycler_view.setAdapter(clerkAdapter);

            mRefreshLayout = rootView.findViewById(R.id.refreshLayout);
            //设置 Header 为 贝塞尔雷达 样式
            mRefreshLayout.setRefreshHeader(new BezierRadarHeader(getActivity()).setEnableHorizontalDrag(true));//BezierRadarHeader
            //设置 Footer 为 球脉冲 样式
            mRefreshLayout.setRefreshFooter(new ClassicsFooter(getActivity()).setSpinnerStyle(SpinnerStyle.FixedBehind));//BallPulseFooter ClassicsFooter
            mRefreshLayout.setPrimaryColors(AppThemeUtils.getInstance().getRefreshBackgroundColor(),AppThemeUtils.getInstance().getRefreshAccessColor());
            mRefreshLayout.setEnableRefresh(true);//启用刷新
            mRefreshLayout.setEnableLoadMore(true);//启用加载
            //刷新
            mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
                @Override
                public void onRefresh(RefreshLayout refreshlayout) {
                    //refreshlayout.finishRefresh();
                    pageindex = 0;
                    getData();
                }
            });
            mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
                @Override
                public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                    //refreshLayout.finishLoadMore();
                    getData();
                }
            });
            getData();
        }else {
            //缓存的rootView需要判断是否已经被加过parent， 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (parent != null) {
                parent.removeView(rootView);
            }
        }
        return rootView;
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        calculateImageWidth();
    }

    private void calculateImageWidth() {
        int width = ScreenUtils.getScreenWidth(getActivity());
        int margin = getResources().getDimensionPixelSize(R.dimen.paddingLR);
        imgW = width - margin * 2;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    public void getFirstData(boolean isFirst){
        if (getActivity() == null){
            return;
        }
        if (clerk_recycler_view == null || clerkAdapter == null){
            return;
        }
        if (clerkAdapter.mList.size() == 0){
            if (mRefreshLayout != null){
                pageindex = 0;
                mRefreshLayout.autoRefresh();
            }
        }else {
            if (isFirst == true){
                //listview.smoothScrollToPosition(0);
                //listview.setSelection(0);
            }
        }
    }

    private void getData(){
        if (clerk_recycler_view == null || clerkAdapter == null){
            return;
        }
        new Thread(){
            @Override
            public void run() {
                super.run();
                //首次从缓存里面获取数据
                if (clerkAdapter.mList.size() == 0 && pageindex == 0){
                    String data = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.ClertData,"");
                    if (!CommonUtils.isEmpty(data)){
                        final List<LangInfoModel> l = GsonTools.getUserLangInfoModel(data);
                        if (getActivity() == null){
                            return;
                        }
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (l != null && l.size() > 0){
                                    clerkAdapter.mList.addAll(l);
                                }
                                clerkAdapter.notifyDataSetChanged();
                            }
                        });
                    }
                }


                final HashMap<String, String> map = new HashMap<String, String>();
                if(CommonUtils.isLogin() == true){
                    map.put(APIKey.tokenKey, CommonUtils.formatString(CustomApplication.loginModel.getToken()));
                }
                map.put("dataType","0");
                map.put("pageIndex",pageindex+"");
                map.put("pageRecord",Records+"");
                HttpsUtils.miniAppDo(map, "clerk/list.do", new HttpCallBack() {
                    @Override
                    public void onSuccess(final String data) {
                        Log.e("TAG","文案："+data);
                        final CommonModel commonModel = GsonTools.getCommonModel(data);
                        if (commonModel.getFlag().equals("1")){
                            final List<LangInfoModel> l = GsonTools.getUserLangInfoModel(data);
                            if (getActivity() == null){
                                return;
                            }
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (mRefreshLayout.getState() == RefreshState.Loading){
                                        mRefreshLayout.finishLoadMore();
                                    }else {
                                        clerkAdapter.mList.clear();
                                        mRefreshLayout.finishRefresh();
                                    }
                                    if (l != null && l.size() > 0){
                                        if (pageindex == 0){
                                            SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.ClertData,data);
                                        }
                                        if (l.size() >= Records){
                                            mRefreshLayout.setEnableLoadMore(true);
                                        }else {
                                            mRefreshLayout.setEnableLoadMore(false);
                                        }
                                        clerkAdapter.mList.addAll(l);
                                    }else {
                                        isHasMore = false;
                                        mRefreshLayout.setEnableLoadMore(false);
                                    }
                                    clerkAdapter.notifyDataSetChanged();
                                }
                            });
                        }else {
                            if (getActivity() == null){
                                return;
                            }
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (mRefreshLayout.getState() == RefreshState.Loading){
                                        //listview.stopLoadMore();
                                        mRefreshLayout.finishLoadMore();
                                    }else {
                                        //listview.stopRefresh(true);
                                        mRefreshLayout.finishRefresh();
                                    }
                                    CustomApplication.showTip(commonModel, getActivity());
                                }
                            });
                        }
                    }

                    @Override
                    public void onError(String msg) {
                        if (getActivity() == null){
                            return;
                        }
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (mRefreshLayout.getState() == RefreshState.Loading){
                                    //listview.stopLoadMore();
                                    mRefreshLayout.finishLoadMore();
                                }else {
                                    //listview.stopRefresh(true);
                                    mRefreshLayout.finishRefresh();
                                }
                            }
                        });
                    }
                });
            }
        }.start();

    }

}
